package com.fhz.a2102shopjava.ui.mine;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.fhz.a2102shopjava.R;
import com.fhz.a2102shopjava.base.BaseFragment;
import com.fhz.a2102shopjava.base.BaseNoViewModelFragment;
import com.fhz.a2102shopjava.bus.MessageEvent;
import com.fhz.a2102shopjava.callback.ApiResponse;
import com.fhz.a2102shopjava.cons.Cons;
import com.fhz.a2102shopjava.databinding.FragmentHomeBinding;
import com.fhz.a2102shopjava.databinding.FragmentMineBinding;
import com.fhz.a2102shopjava.qiniu.QiNiuUploadManager;
import com.fhz.a2102shopjava.ui.home.HomeViewModel;
import com.fhz.a2102shopjava.ui.imagepicker.ImagePickerActivity;
import com.fhz.a2102shopjava.ui.login.ui.login.LoginActivity;
import com.fhz.a2102shopjava.util.ImageLoader;
import com.github.gzuliyujiang.imagepicker.ActivityBuilder;
import com.github.gzuliyujiang.imagepicker.CropImageView;
import com.github.gzuliyujiang.imagepicker.ImagePicker;
import com.github.gzuliyujiang.imagepicker.PickCallback;
import com.tencent.mmkv.MMKV;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class MineFragment extends BaseNoViewModelFragment<MineViewModel, FragmentMineBinding> {

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_mine;
    }
    String headImage;
    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
        MMKV mmkv = MMKV.defaultMMKV();
        String username = mmkv.decodeString("username","");
        headImage = mmkv.decodeString("headImage","");
        if(username.equals("")){
            LoginActivity.launch(getActivity());
        }


        //加载默认头像
        ImageLoader.loadCircle(getActivity(),headImage,mBinding.mainImgHead);

        //更换头像
        mBinding.mainImgHead.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), ImagePickerActivity.class));
        });

        //退出登录
        mBinding.mineBtnLogout.setOnClickListener(v -> {
            mmkv.clear();
            Navigation.findNavController(getActivity(),R.id.nav_host_fragment_activity_nav).navigate(R.id.navigation_home);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MMKV mmkv = MMKV.defaultMMKV();
        String username = mmkv.decodeString("username","");
        headImage = mmkv.decodeString("headImage","");
        //加载默认头像
        ImageLoader.loadCircle(getActivity(),headImage,mBinding.mainImgHead);

    }

    @Override
    protected MineViewModel createViewModel() {
        return  mViewModel = new ViewModelProvider(this).get(MineViewModel.class);
    }

    /**
     * 更新头像
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventBusMessage(MessageEvent messageEvent){
        Glide.with(this).load(messageEvent.getMessage()).circleCrop().into(mBinding.mainImgHead);

        System.out.println(messageEvent.getMessage());
        mViewModel.getQiNiuToken().observe(this, new Observer<ApiResponse<String>>() {
            @Override
            public void onChanged(ApiResponse<String> stringApiResponse) {
                //开启头像上传,到后台和七牛云.主要裁剪后文件的缓存位置.
                QiNiuUploadManager.getQiNiuUploadManager()
                        .getUploadManager()
                        .put(deleteFileFix(
                                messageEvent.getMessage()), //文件名
                                generateFileName(),//上传七牛后生成的文件名,也是要存入到后端的地址,加上http
                                stringApiResponse.getData(), (key, info, res) -> {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if(info.isOK()) {
                                Log.i("qiniu", "Upload Success");
                                System.out.println(key);
                                //更新后端的用户的地址,下次登录,直接换.
                                MMKV mmkv = MMKV.defaultMMKV();
                                String username = mmkv.decodeString("username", "");
                                mViewModel.updateUserAvatar(username, Cons.QINIU_URL.concat(key)).observe(MineFragment.this, new Observer<ApiResponse<String>>() {
                                    @Override
                                    public void onChanged(ApiResponse<String> stringApiResponse) {
                                        //重新加载头像
                                        ImageLoader.loadCircle(getActivity(),Cons.QINIU_URL.concat(key),mBinding.mainImgHead);

                                    }
                                });

                            } else {
                                Log.i("qiniu", "Upload Fail");
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            }
                            Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);
                        }, null);

            }
        });
    }

    /**
     * 格式化一下文件 去掉file:///
     */
    public String deleteFileFix(String s){
        return s.substring(8);
    }

    /**
     * 生成上传的文件名
     * @return
     */
    private String generateFileName() {
        String username = MMKV.defaultMMKV().getString("username", "");
        long l = System.currentTimeMillis();
        return String.valueOf(l).concat("_").concat(username);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}